package net.flowas.modulecart.rest;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import net.flowas.modulecart.domain.Category;

/**
 * 
 */
// @Path("/categories")
public class CategoryEndpoint extends AbstractEndpoint<Category> {
	private EntityManager em = Persistence.createEntityManagerFactory("cartPU")
			.createEntityManager();
	@GET
	@Path("/{id:[0-9][0-9]*}")
	@Produces("application/json")
	public Category findById(@PathParam("id") Long id) {
		TypedQuery<Category> findByIdQuery = em
				.createQuery(
						"SELECT DISTINCT c FROM Category c LEFT JOIN FETCH c.parent LEFT JOIN FETCH c.children WHERE c.id = :entityId ORDER BY c.id",
						Category.class);
		findByIdQuery.setParameter("entityId", id);
		Category entity;
		try {
			entity = findByIdQuery.getSingleResult();
		} catch (NoResultException nre) {
			entity = null;
		}
		if (entity == null) {
			//return Response.status(Status.NOT_FOUND).build();
		}
		return entity;
	}

	@GET
	@Path("list.json")
	@Produces("application/json")
	public List<Category> listAll(@QueryParam("start") Integer startPosition,
			@QueryParam("max") Integer maxResult) {
		TypedQuery<Category> findAllQuery = em
				.createQuery(
						"SELECT DISTINCT c FROM Category c LEFT JOIN FETCH c.parent LEFT JOIN FETCH c.children ORDER BY c.id",
						Category.class);
		if (startPosition != null) {
			findAllQuery.setFirstResult(startPosition);
		}
		if (maxResult != null) {
			findAllQuery.setMaxResults(maxResult);
		}
		final List<Category> results = findAllQuery.getResultList();
		return results;
	}

	@Override
	protected Class<Category> getType() {
		return Category.class;
	}
}